<template>
	<view class="wxlogin_box">
		<image class="img" src="../../static/logo.png" mode="scaleToFill"></image>
		<button class="text" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">手机号快捷登录</button>
		<!-- <button class="text" @click="fn4">微信登录</button> -->
		<!-- <button class="text" @click="fn1">获取用户信息</button> -->
	</view>
</template>

<script>
	import CryptoJS from 'crypto-js';
	export default {
		data() {
			return {
				mobile: null,
				dl_but: false,
				wx_code: null,
				session_key: null,
				wx_sessionKey: null, //用户密钥，跟openid同一个接口的
				wx_phoneNumber: "", //电话号码
				appid: null,
				secret: null,
				grant_type: null,
				longin_true: false,
				encryptedData: null,
				iv: null,
			};
		},
		methods: {

			// 第一步获取手机号码
			getPhoneNumber(e) {
				console.log(e.detail.encryptedData, "获取电话数据");
				this.wx_inif(e)
			},
			
			wx_inif(e) {
				uni.$http.get('/index/info').then(res => {
					console.log(res.data.data);
					this.appid = res.data.data.appId
					this.secret = res.data.data.secret
					this.grant_type = res.data.data.grant_type
					this.wx_loin(e)
				})
			},
			// 第二步获取登录凭证	
			wx_loin(e) {
				uni.login({
					provider: 'weixin',
					success: res_code => {
						this.wx_code = res_code.code
						uni.$http.get('/index/getSessionKey', {
							code: this.wx_code
						}).then(getSessionKey => {
							this.wx_sessionKey = getSessionKey.data.data.session_key
							console.log(e.detail.encryptedData, "登录加密1");
							console.log(e.detail.iv, "登录加密2");
							this.encryptedData = e.detail.encryptedData
							this.iv = e.detail.iv
							// 使用解密函数进行解密
							let data = this.decryptData(this.appid, this.wx_sessionKey, this
								.encryptedData, this.iv);
							// 解密手机号码 data.phoneNumber
							this.wx_phoneNumber = data.phoneNumber
							console.log(this.wx_phoneNumber, "电话号码");
							// 获取用户信息
							uni.getUserInfo({
								provider: 'weixin',
								success: (infoRes) => {

									console.log(infoRes, '获取用户信息');
									if (infoRes.errMsg === 'getUserInfo:ok') {
										// 用户同意了获取用户信息
										let userInfo = infoRes
											.userInfo; // 用户的公开信息（昵称、头像等）

										// 发送 GET 请求，获取登录参数
										uni.$http.get('/index/info', {
											code: res_code.code
										}).then(infoRes => {
											// 登录注册参数
											let formData = {
												mobile: this
													.wx_phoneNumber, // 这里是解密得到的电话号码
												photo: userInfo
													.avatarUrl,
												nickname: `${userInfo.nickName}${this.wx_phoneNumber}`,
												unionid: infoRes.data
													.data.appId
											};

											uni.$http.post(
												'/index/authorize',
												formData).then(
												authRes => {
													// 在这里，如果服务器返回了用户的 token，你应该将它保存到本地，然后在后续的请求中使用
													console.log(
														authRes
														.data,
														"返回数据");
													this.longin_true =
														true
													if (authRes.data.code ==
														0) {
														uni.showToast({
															title: `${authRes.data.msg}`,
															duration: 3000,
															icon: 'none'
														});
														return
													}
													// 在这里，如果服务器返回了用户的 token，你应该将它保存到本地，然后在后续的请求中使用
													if (authRes.data
														.data) {
														uni.setStorageSync(
															'wx_user_token',
															authRes
															.data
															.data);
													}
													uni.switchTab({
														url: '/pages/home/home'
													});
													// uni.navigateBack();
													// uni.navigateBack({
													// 	delta: 2
													// });

												}).catch(authErr => {
												console.log(
													authErr);
											});
										}).catch(infoErr => {
											console.log(infoErr);
										});
									} else {
										// 用户拒绝了获取用户信息
										uni.showModal({
											title: '提示',
											content: '为了更好的体验，需要您同意授权',
											showCancel: false
										});
									}
								}
							});
						})
					}
				});
			},

			decryptData(appId, sessionKey, encryptedData, iv) {
				console.log('appId',appId,'sessionKey:',sessionKey,'encryptedData：',encryptedData,'iv:',iv)
				let timerId = setTimeout(() => {
					uni.showToast({
						title: "微信授权失败,请重新登录!",
						duration: 4000,
						icon: 'none'
					});
				}, 2500);
				var key = CryptoJS.enc.Base64.parse(sessionKey);
				var encryptedWordArray = CryptoJS.enc.Base64.parse(encryptedData);
				iv = CryptoJS.enc.Base64.parse(iv);

				var decrypted = CryptoJS.AES.decrypt({
						ciphertext: CryptoJS.lib.WordArray.create(encryptedWordArray.words)
					},
					key, {
						iv: iv,
						mode: CryptoJS.mode.CBC,
						padding: CryptoJS.pad.Pkcs7
					}
				);

				let decryptedString = decrypted.toString(CryptoJS.enc.Utf8);
				let decoded;
				try {
					decoded = JSON.parse(decryptedString);
					clearTimeout(timerId)
				} catch (err) {
					console.error('Decryption resulted in invalid JSON:', err);

				}
				return decoded;
			},

		}
	}
</script>

<style lang="scss">
	.wxlogin_box {
		width: 100%;
		height: 100vh;
		background-color: #ffffff;
		position: relative;

		.img {
			width: 160rpx;
			height: 80px;
			position: absolute;
			left: 50%;
			top: 35%;
			transform: translatex(-50%);
		}

		.text {
			width: 80%;
			height: 100rpx;
			padding: 15rpx 0;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #76B9FE !important;
			border-radius: 62rpx 62rpx 62rpx 62rpx;
			font-size: 40rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #FFFFFF;
			// letter-spacing: 10px;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translateX(-50%);
		}
	}
</style>